import os.path
import shutil
from typing import List

from PyQt6.QtGui import QDragEnterEvent, QDropEvent, QIntValidator
from PyQt6.QtWidgets import QWidget, QPushButton, QLabel, QTextEdit, QScrollArea, QLineEdit
from PyQt6.uic import loadUi

import main_model
from global_config import *
from scripts import db_utils
from scripts.beans import Storyboard
from ui.DrawPage import DrawPage
from ui.adapters.ScrollviewAdapter import ScrollviewAdapter
from ui.widgets.notice_dialog import ConfirmDialog


class BoardPage(QWidget):
    def __init__(self):
        super().__init__()
        self.draw_page = None
        self.storyboards: List[Storyboard] = None
        self.import_srt_btn: QPushButton = None
        self.save_btn: QPushButton = None
        self.split_board_btn: QPushButton = None
        self.gpt_board_btn: QPushButton = None
        self.srt_label: QTextEdit = None
        self.board_listview: QScrollArea = None
        self.count_et: QLineEdit = None
        self.listAdapter: ScrollviewAdapter = None
        self.initView()

    def initView(self):
        loadUi('./source/board_page.ui', self)
        self.count_et.setValidator(QIntValidator(0, 9999, self))
        self.listAdapter = ScrollviewAdapter(self.board_listview, True,
                                             self.on_merge_srt)
        self.srt_label.setAcceptDrops(True)
        self.setAcceptDrops(True)
        self.split_board_btn.clicked.connect(lambda: (self.split_boards(True)))
        self.gpt_board_btn.clicked.connect(lambda: (self.gpt_split_boards()))
        self.save_btn.clicked.connect(self.save_boards)
        self.import_srt_btn.hide()
        self.srt = get_srt_path()
        if os.path.exists(self.srt):
            with open(self.srt, 'r', encoding='utf-8') as file:
                self.srt_label.setText(file.read())
            self.split_boards(False)

    def on_merge_srt(self, command, index):
        if command == 1:  # merge up
            last = index - 1
            if last >= 0:
                indexbean = self.storyboards[index]
                lastbean = self.storyboards[last]
                self.storyboards.remove(indexbean)
                lastbean.srtbean = lastbean.srtbean + indexbean.srtbean
                self.load_storyboards(self.storyboards, index)

        elif command == 2:  # merge down
            next = index + 1
            if next < len(self.storyboards):
                indexbean = self.storyboards[index]
                nextbean = self.storyboards[next]
                self.storyboards.remove(nextbean)
                indexbean.srtbean = indexbean.srtbean + nextbean.srtbean
                self.load_storyboards(self.storyboards, index)
        elif command == 3:  # split board
            indexbean = self.storyboards[index]
            self.storyboards.remove(indexbean)
            for v in reversed(indexbean.srtbean):
                newBoard = Storyboard(v['start'], v['end'], v['text'], None, None)
                self.storyboards.insert(index, newBoard)
            self.load_storyboards(self.storyboards, index)

    def save_boards(self):
        if self.storyboards is not None:
            db_utils.save_wordflow(get_storyboards_path(), self.storyboards)

    def import_srt(self, srt_path):
        msg = ''
        if srt_path == '':
            msg = '请输入字幕路径。'
        elif srt_path is not None:
            shutil.copy(srt_path, self.srt)
            with open(self.srt, 'r', encoding='utf-8') as file:
                self.srt_label.setText(file.read())

        if msg != '':
            dialog = ConfirmDialog('提示', msg)
            result = dialog.get_result()

    # 根据srt文件，分割分镜
    def split_boards(self, resplit):
        if not os.path.exists(self.srt):
            ConfirmDialog('提示', '请导入原视频和字幕文件').get_result()
            return

        # self.loading.show()
        def callback():
            self.storyboards = db_utils.read_workflow(get_storyboards_path())
            self.load_storyboards(self.storyboards)
            # self.loading.hide()

        main_model.parse_srt2storyboard(callback, int(self.count_et.text()), resplit)

    # gpt 帮助分镜
    def gpt_split_boards(self):
        ConfirmDialog('提示', '开发中').get_result()

    # 加载解析完的 分镜数据
    def load_storyboards(self, storyboards, index=0):
        print(self.listAdapter)
        self.listAdapter.load(storyboards, index)

    def dragEnterEvent(self, e: QDragEnterEvent):
        e.acceptProposedAction()

    def dropEvent(self, e: QDropEvent):
        for url in e.mimeData().urls():
            file_name = url.toLocalFile()
            if 'srt' in file_name:
                self.import_srt(file_name)
